//
//  Extensions.swift
//  全国高等学校查询
//
//  Created by 高宇超 on 6/14/17.
//  Copyright © 2017 Yuchao. All rights reserved.
//

import Foundation
import UIKit


// MARK :- String
extension String {
    
    // appending an integer
    func appending(int: Int) -> String {
        return self.appending("\(int)")
    }
    
    // remove all white spaces
    func removeSpaces() -> String {
        return self.components(separatedBy: .whitespaces).joined()
    }
    
    // parse html 
    func percentEncoding() -> String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
    }
}

// MARK :- ViewController
extension UIViewController {
    
    func alertOkay(title: String = "", msg: String, action: @escaping (UIAlertAction) -> Void) {
        let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert)
        let okayAction = UIAlertAction(title: "👌", style: .default, handler: action)
        alertController.addAction(okayAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func alertOkayAndCancel(title: String = "", msg: String, action: @escaping (UIAlertAction) -> Void) {
        let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert)
        let okayAction = UIAlertAction(title: "确定", style: .destructive, handler: action)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alertController.addAction(okayAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
}

// MARK :- UIView 
extension UIView {
    
    // notification (id is useless for now)
    static func notifyc(label: UILabel, text: String, color: YColor = .green, duration: TimeInterval = 1, delay: TimeInterval = 1, id: Int = 0) -> Void {
        if !NormalVC.usingNotifyLabel {
            NormalVC.usingNotifyLabel = true
            label.text = "\n\(text)"
            label.backgroundColor = colors[color]
            UIView.animate(withDuration: 0.2, delay: delay, options: [.curveEaseInOut], animations: {
                label.frame.origin.y = 0
                label.alpha = 1
            }, completion: {
                finished in
                if finished {
                    UIView.dismissNotify(label: label, delay: duration, id: id)
                }
            })
        }
    }
    static func dismissNotify(label: UILabel, delay: TimeInterval = 0, id: Int = 0) {
        UIView.animate(withDuration: 0.2, delay: delay, options: [.curveEaseOut], animations: {
            label.frame.origin.y = -64
            label.alpha = 0.4
        }, completion: {
            finished in
            if finished {
                NormalVC.usingNotifyLabel = false
            }
        })
    }
    
}

// MARK :- Button
extension UIButton {
    
    func show(duration: TimeInterval, delay: TimeInterval = 0) {
        UIView.animate(withDuration: duration, delay: delay, options: [.curveEaseInOut], animations: {
            self.alpha = 1
        }, completion: {
            finished in
            if finished {
                self.isEnabled = true
            }
        })
    }
    
    func hide(duration: TimeInterval, delay: TimeInterval = 0) {
        self.isEnabled = false
        UIView.animate(withDuration: duration, delay: delay, options: [.curveEaseInOut], animations: {
            self.alpha = 0
        })
    }

}


// MARK :- WebView, grab information from html
extension UIWebView {

    func rtrvSchools() -> [String] {
        stringByEvaluatingJavaScript(from: "var script = document.createElement('script');script.type = 'text/javascript';script.text = function rtrvSchools() {var table = document.getElementsByClassName('lin-seachtable')[0];var trArr = table.getElementsByClassName('lin-gettr');for (tr in trArr) {str = str + trArr[tr].innerText + ';'}; return str;};document.getElementsByTagName('head')[0].appendChild(script);")
        guard let set = self.stringByEvaluatingJavaScript(from: "rtrvSchools();") else { return [] }
        var array = set.components(separatedBy: CharacterSet(charactersIn: ";"))
        array = array.filter({ $0 != "undefined" && $0 != "" && $0.contains("\t") })
        if let first = array.first {
            if first.hasPrefix("undefined") {
                array[0] = first.substring(from: first.index(first.startIndex, offsetBy: 9))
            }
        }
        array.distinct()
        return array
    }
    
    func rtrvBaikeLink() -> String {
        stringByEvaluatingJavaScript(from: "var script = document.createElement('script');script.type = 'text/javascript';script.text = function rtrvBaikeLink() { var divs = document.getElementsByTagName('div'); for (div in divs) { if(div.innerHTML.indexOf('baike.baidu.com') >= 0) { return div.innerHTML } } return ''; }; document.getElementsByTagName('head')[0].appendChild(script);")
        guard let str = self.stringByEvaluatingJavaScript(from: "rtrvBaikeLink();") else { return "" }
        return str
    }
    
}

// MARK :- Array
extension Array where Element: Equatable {
    
    // distinct
    mutating func distinct() {
        var uniqueArr: [Element] = []
        for elem in self {
            if !uniqueArr.contains(elem) {
                uniqueArr.append(elem)
            }
        }
        self = uniqueArr
    }
    
}

// MARK :- Device
public extension UIDevice {
    
    var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") {
            identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        
        switch identifier {
        case "iPod5,1":                                 return "iPod Touch 5"
        case "iPod7,1":                                 return "iPod Touch 6"
        case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
        case "iPhone4,1":                               return "iPhone 4s"
        case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
        case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
        case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
        case "iPhone7,2":                               return "iPhone 6"
        case "iPhone7,1":                               return "iPhone 6 Plus"
        case "iPhone8,1":                               return "iPhone 6s"
        case "iPhone8,2":                               return "iPhone 6s Plus"
        case "iPhone9,1", "iPhone9,3":                  return "iPhone 7"
        case "iPhone9,2", "iPhone9,4":                  return "iPhone 7 Plus"
        case "iPhone8,4":                               return "iPhone SE"
        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
        case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
        case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
        case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
        case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
        case "iPad6,11", "iPad6,12":                    return "iPad 5"
        case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
        case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
        case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
        case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
        case "iPad6,3", "iPad6,4":                      return "iPad Pro 9.7 Inch"
        case "iPad6,7", "iPad6,8":                      return "iPad Pro 12.9 Inch"
        case "iPad7,1", "iPad7,2":                      return "iPad Pro 12.9 Inch 2. Generation"
        case "iPad7,3", "iPad7,4":                      return "iPad Pro 10.5 Inch"
        case "AppleTV5,3":                              return "Apple TV"
        case "i386", "x86_64":                          return "Simulator"
        default:                                        return identifier
        }
    }
    
}




